from http_evented import http_evented
from collections import deque
import urllib
import logging

class master_notifier(http_evented):
    """
    This class is responsible for notifying the master node in a
    pymq cluster about it's availability, status and other
    details such as it's name, etc...
    It also lets the master node know about queue additions/deletions
    """
    def __init__(self, host_and_port, onConnected=None,
                 onClose=None, onException=None):
        http_evented.__init__(self, host_and_port, onConnected,
                              onClose, onException)
        self._nextRequestID = 1
        self.numPendingResponses = 0

    def nextRequestID(self):
        self._nextRequestID += 1
        return self._nextRequestID - 1

    def tryPoppingResponse(self):
        self.numPendingResponses += 1
        if self.numPendingResponses == 1:
            self.pop_response()

    def onResponseReceived(self):
        self.numPendingResponses -= 1
        if self.numPendingResponses > 0:
            self.pop_response()

    def send_availability(self, nodeName, nodeHost, nodePort,
                          nodeState, connectionString,
                          onAvailabilitySentConfirmed=None):
        url = "/node/register/%s/%s/%d/%s/" % (nodeName, nodeHost, nodePort, nodeState)
        if nodeState == "active":
            url += "?" + urllib.urlencode({ "connectionString": connectionString })

        self.make_HTTP_request("GET", url=url, body="",
                               headers={ 'X-Sequence': self.nextRequestID() },
                               callback=onAvailabilitySentConfirmed)

    def queue_added(self, queueName):
        url = "/queue/%s/addQueue/" % queueName
        self.push_HTTP_request("GET", url=url, body="",
                               headers={ 'X-Sequence': self.nextRequestID() },
                               callback=self.onResponseReceived)
        self.tryPoppingResponse()

    def queue_dropped(self, queueName):
        url = "/queue/%s/dropQueue/" % queueName
        self.push_HTTP_request("GET", url=url, body="",
                               headers={ 'X-Sequence': self.nextRequestID() },
                               callback=self.onResponseReceived)
        self.tryPoppingResponse()

class run_proc(object):
    def __init__(self, proc):
        self.proc = proc

    def done(self):
        """
        This function is called when the caller wants to send the request out
        """
        logging.debug("run_proc::done")
        self.proc()
